package cn.kduck.plugin.idea;

import cn.kduck.plugin.idea.dialog.GenerateMapBeanDialog;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;

public class KduckMapBeanAction extends AnAction {

    private PsiClass containingClass;

    @Override
    public void update(@NotNull AnActionEvent e) {
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
        if(file instanceof PsiJavaFile){
            int offset = editor.getCaretModel().getOffset();
            containingClass = PsiTreeUtil.getParentOfType(file.findElementAt(offset), PsiClass.class);
            if(containingClass != null && !containingClass.isEnum() && !containingClass.isInterface() && containingClass.getName() != null){
                e.getPresentation().setVisible(true);
                return;
            }
        }
        e.getPresentation().setVisible(false);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();
//        Editor editor = e.getData(CommonDataKeys.EDITOR);

//        PsiClass[] innerClasses = containingClass.getInnerClasses();
//        for (PsiClass innerClass : innerClasses) {
//            System.out.println(containingClass.getName() + "有内部类："+innerClass.getName()+",isEnum = " + innerClass.isEnum() +"，type=" + innerClass);
//        }

        GenerateMapBeanDialog generateMapBeanDialog = new GenerateMapBeanDialog(project,containingClass);

        PsiField[] allFields = containingClass.getFields();
        for (PsiField allField : allFields) {
            PsiModifierList modifierList = allField.getModifierList();
            if(modifierList.hasExplicitModifier(PsiModifier.STATIC)
            || modifierList.hasExplicitModifier(PsiModifier.FINAL)){
                continue;
            }

            PsiMethod setterForField = PropertyUtil.findSetterForField(allField);
            PsiMethod getterForField = PropertyUtil.findGetterForField(allField);

            if(setterForField == null || getterForField == null){
                generateMapBeanDialog.addField(allField);
            }
        }
        generateMapBeanDialog.selectAll();

        generateMapBeanDialog.showAndGet();
    }
}
